package com.mjk.manager.amis.core.controller;

import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import com.mjk.common.base.error.BeeError;
import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.core.jdbc.service.plus.idbservice.BeeDBService;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeComplexQueryWrapper;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeQueryWrapper;
import com.mjk.common.core.redis.datatype.RedisUtils;
import com.mjk.common.tools.encrypt.MD5Util;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.util.ClobUtils;
import com.mjk.common.util.TreeUtils;
import com.mjk.manager.amis.AmisModelInfo;
import com.mjk.manager.amis.constans.Constants;
import com.mjk.manager.amis.core.dto.SessionDetails;
import com.mjk.manager.amis.core.model.PlatUser;
import com.mjk.manager.amis.core.model.SysMenu;
import com.mjk.manager.amis.core.model.SysRoleMenu;
import com.mjk.manager.amis.core.utils.SessionHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 登入
 */
@Controller
public class AmisLoginController {

    @Autowired
    private BeeDBService beeDBService;
    @Autowired
    private SessionHolder sessionHolder;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 打开登入界面 默认ID =3；
     * @param request
     * @param response
     * @param model
     * @param redirect
     * @return
     */
//    @GetMapping("/login")
//    public String login(HttpServletRequest request, HttpServletResponse response, Model model,
//                        @RequestParam(name = "redirect", required = false) String redirect) {
//        BeeQueryWrapper wrapper = new BeeQueryWrapper(new AmisModelInfo());
//        wrapper.eq(AmisModelInfo::getId, 4);
//        AmisModelInfo info = (AmisModelInfo) beeDBService.findOneByWrapper(wrapper);
//        if (null != info && null != info.getInfo()) {
//            model.addAttribute("json", ClobUtils.clobToString(info.getInfo()));
//        } else {
//            model.addAttribute("json", "{}");
//        }
//
//        model.addAttribute("contextPath", getContextPath(request));
//
//        return "page";
//    }

    /**
     * 界面验证码接口
     * @param request
     * @param response
     */
    @GetMapping(value = {"/captcha.png", "captcha"})
    public void captcha(@NotNull HttpServletRequest request, HttpServletResponse response) {
        final HttpSession session = request.getSession();

        AbstractCaptcha captcha = CaptchaUtil.createShearCaptcha(150, 37, 4, 3);
        String code = captcha.getCode();
        RedisUtils.set(redisTemplate,Constants.CAPTCHA_CODE,code);
        RedisUtils.set(redisTemplate,Constants.CAPTCHA_TIMEOUT,System.currentTimeMillis() + 5 * 60 * 1000);
//        session.setAttribute(Constants.CAPTCHA_CODE, code);
//        session.setAttribute(Constants.CAPTCHA_TIMEOUT, System.currentTimeMillis() + 5 * 60 * 1000);
        try {
            captcha.write(response.getOutputStream());
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping(path = "/login")
    @ResponseBody
    public BeeResponse login(HttpServletRequest request, HttpServletResponse response,
                             @RequestBody Map<String, String> data) {
        final HttpSession session = request.getSession();

        String captchaCode = (String) session.getAttribute(Constants.CAPTCHA_CODE);
        Long captchaTimeout = (Long) session.getAttribute(Constants.CAPTCHA_TIMEOUT);

        final String username = data.get("username");
        final String password = data.get("password");
        final String captcha = data.get("captcha");

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return BeeError.LOGIN_ERROR_ACCOUNT_NOT_EXIT.tranceError();
        }

        if (StringUtils.isBlank(captcha)) {
            return BeeError.LOGIN_ERROR_CHECKCODE_ERROR.tranceError();
        }

        if (StringUtils.isBlank(captchaCode) || captchaTimeout == null || captchaTimeout < System.currentTimeMillis()
                || !captchaCode.equalsIgnoreCase(captcha)) {
            return BeeError.LOGIN_ERROR_CHECKCODE_ERROR.tranceError();
        }
        BeeQueryWrapper wrapper = new BeeQueryWrapper(new PlatUser());
        wrapper.eq(PlatUser::getLOGIN_NAME, username);
        List<PlatUser> users = beeDBService.findManyByWrapper(wrapper);
        if (CollectionUtils.isEmpty(users)) {
            return BeeError.LOGIN_ERROR_CHECKCODE_ERROR.tranceError();
        }
        PlatUser user = users.get(0);

        if (!MD5Util.lowMd5(user.getPASSWORD()).equals(password)) {
            return BeeError.LOGIN_ERROR_PWD_ERROR.tranceError();
        }

        if (user.getSTATUS() != 1) {
            return BeeError.LONIN_ERROR_STATUS_ERROR.tranceError();
        }
        //登入用户的菜单信息
        BeeComplexQueryWrapper wrapper1 = new BeeComplexQueryWrapper(SysMenu.class,"a");
        wrapper1.innerJoin(SysRoleMenu.class,"b").on(SysMenu::getId,SysRoleMenu::getMENU_ID);
        wrapper1.in(SysRoleMenu::getROLE_ID, Arrays.asList(user.getRoles().split(",")));
        wrapper1.eq(SysRoleMenu::getDELETED,false);
        wrapper1.orderBy(" a.seq ");
        List<SysMenu> menus = beeDBService.findManyByComplexWrapper(wrapper1);
        List<SysMenu> menuTree = TreeUtils.list2Tree(menus, "0", "id", "PID", "children", false);

        SessionDetails details = sessionHolder.newSession(request, user);
        details.setMenus(menuTree);
        StpUtil.login(user.getId());//登入用户
        return BeeError.BEE_SUC.tranceError(details);
    }

    @RequestMapping("/loginout")
    @ResponseBody
    public BeeResponse loginout(HttpServletRequest request, HttpServletResponse response) {
        // 退出本地登录
        sessionHolder.clearSession(request);
//        try {
            StpUtil.logout();//登出
//            response.sendRedirect("/login");
//        } catch (IOException e) {
//            BizLogger.error(e.getLocalizedMessage(), e);
//        }
        return BeeError.BEE_SUC.tranceError();
    }
    private String getContextPath(HttpServletRequest request) {
        return request.getContextPath();
    }
}
